#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from typing import Any, List, Dict,Optional
from pydantic import BaseModel
from fastapi import APIRouter
from jinja2 import Template
from core.base_agent import BaseAgent
from models.doubao import DoubaoModel, logger


class StatusRequest(BaseModel):
    """
    表单信息识别与更新请求模型
    
    :param conversations: 聊天历史记录
    :param form: 当前表单状态
    """
    conversations: List[Dict[str, str]]
    form: Dict[str, Any] = {}
    category: str
    subcategory: str
    cooperation_status:str

class StatusResponse(BaseModel):
    """
    表单信息识别与更新响应模型
    
    :param updated_category: 大类
    :param updated_subcategory: 小类
    """
    updated_cooperation_status:str
    updated_category:str
    updated_subcategory:str
    success: bool
    message: str

class StatusAgent(BaseAgent):
    """合作状态识别与更新智能体"""
    
    def __init__(self):
        super().__init__(name="status_confirmation_Agent")
        self.name = "合作状态识别智能体"
        self.description = "专门负责识别聊天记录中博主合作状态的系统"
        self.doubao_client = DoubaoModel()
        # self._setup_routes()
    
    def _setup_routes(self) -> None:
        """设置路由"""
        router = APIRouter(prefix=f"/{self.__class__.__name__.lower().replace('agent', '')}")
        router.post("/Status_confirmation", response_model=StatusResponse)(self.process)
        self.router = router
    
    async def process(self, data: dict[str, Any]) -> dict[str, Any]:
        """
        处理合作状态识别与更新
        
        :param data: 包含聊天历史和当前表单状态的数据
        :return: 处理结果
        """
        try:
            conversations = data.get("conversations", [])
            current_form = data.get("form", {})
            current_category = data.get("category", "")
            current_subcategory = data.get("subcategory", "")
            current_cooperation_status=data.get("cooperation_status","")
            # 构建提示词
            prompt = self._build_prompt(conversations, json.dumps(current_form),current_category,current_subcategory,current_cooperation_status)
            
            # 调用大模型进行表单更新
            response = await self.doubao_client.generate_text(prompt)
            result_dict = self._process_response(response)

            # 提取字符串值，处理可能的缺失情况
            updated_category = result_dict.get('updated_category', current_category)
            updated_subcategory = result_dict.get('updated_subcategory', current_subcategory)
            updated_cooperation_status= result_dict.get('updated_cooperation_status',current_cooperation_status)

            # 确保返回字符串类型
            if not isinstance(updated_category, str):
                updated_category = current_category
            if not isinstance(updated_subcategory, str):
                updated_subcategory = current_subcategory
            if not isinstance(current_cooperation_status, str):
                updated_cooperation_status = current_cooperation_status

            return {
                "updated_category": updated_category,
                "updated_subcategory": updated_subcategory,
                "updated_cooperation_status":updated_cooperation_status,
                "success": True,
                "message": "合作状态识别与更新成功"
            }

        except Exception as e:
            logger.error(f"合作状态识别与更新失败: {str(e)}")
            return {
                "updated_category": current_category,  # 出错时返回原始值
                "updated_subcategory": current_subcategory,
                "updated_cooperation_status":current_cooperation_status,
                "success": False,
                "message": f"合作状态识别与更新失败: {str(e)}"
            }

    
    def _build_prompt(self,conversations: List[Dict[str, str]], current_form: str,current_category:str,current_subcategory:str,current_cooperation_status:str) -> Optional[str]:
        """
        构建表单信息识别与更新提示词
        
        :param conversations: 聊天历史记录
        :param current_form: 当前表单状态
        :return: 构建的提示词
        """
        try:
            # 读取 prompt 模板文件
            import os
            current_dir = os.path.dirname(os.path.abspath(__file__))
            prompt_file = os.path.join(current_dir, "status_confirmation.txt")
            
            with open(prompt_file, 'r', encoding='utf-8') as f:
                prompt_template = Template(f.read())
            
            # 替换模板中的占位符
            prompt = prompt_template.render(
                conversations=conversations,
                form=current_form,
                category=current_category,
                subcategory=current_subcategory,
                cooperation_status=current_cooperation_status

            )
            return prompt
            
        except Exception as e:
            logger.error(f"读取 status_confirmation.txt 文件失败: {str(e)}")

    def _process_response(self, response: str) -> Dict[str, Any]:
        """
        处理模型响应
        
        :param response: 模型响应
        :return: 处理后的表单内容或null
        """
        # 清理响应
        try:
            cleaned_response = response.strip()
            if not cleaned_response or cleaned_response.lower() == "null":
                return {}
            return json.loads(cleaned_response)
        except json.JSONDecodeError:
            logger.error(f"无法解析模型响应: {response}")
            return {}
        except Exception as e:
            logger.error(f"处理响应时出错: {str(e)}")
            return {}
    async def status_route(self, request: StatusRequest) -> StatusResponse:
        """
        表单信息识别与更新接口
        
        :param request: 表单信息识别与更新请求
        :return: 表单信息识别与更新响应
        """
        try:
            result = await self.process({
                "conversations": request.conversations,
                "form": request.form,
                "category": request.category,
                "subcategory":request.subcategory,
                "cooperation_status":request.cooperation_status
            })
            return StatusResponse(
                updated_category=result["updated_category"],
                updated_subcategory=result["updated_subcategory"],
                updated_cooperation_status=result["updated_cooperation_status"],
                success=result["success"],
                message=result["message"]
            )
            
        except Exception as e:
            logger.error(f"合作状态识别与更新接口调用失败: {str(e)}")
            return StatusResponse(
                updated_category=request.category,  # 使用请求中的原始值
                updated_subcategory=request.subcategory,  # 使用请求中的原始值\
                updated_cooperation_status=request.cooperation_status,
                success=False,
                message=f"合作状态识别与更新失败: {str(e)}"
            )
